<template>
  <div class="order-wrapper">
    <div class="order-item common-panel">
      <div class="order-left">
        <div class="top-con">
          <div class="title">{{info.name}}</div>
          <div class="desc">
            {{info.abstract}}
          </div>
        </div>
        <div class="bottom-con">
          <div class="price-wrapper">
            <span class="price"><em>￥</em>{{info.price}}</span>
            <span class="line-price">￥{{info.lineation}}</span>
          </div>
        </div>
      </div>
      <div class="order-right" v-if="info.picurl">
        <van-image
          width="100"
          height="100"
          :src="info.picurl[0]"
        />
      </div>
    </div>

      <van-cell-group class="panel-cell">
        <van-cell title="选择就诊者" :value="member" :icon="`${staticPath}/icon_muying@2x.png`" is-link @click="handleShowPopup('member')" />
        <van-cell title="选择服务地址" :value="form.address" :icon="`${staticPath}/icon_dinwei@2x.png`" is-link @click="handleShowPopup('address')" />
        <van-cell title="请选择服务时间" :value="form.call_time" :icon="`${staticPath}/icon_yuyuejilv@2x.png`" is-link @click="timeShow = true" />
      </van-cell-group>

      <van-popup position="bottom" :style="{ height: '100%' }"
      closeable
      close-icon="close"
      v-model="timeShow">
        <div class="time-select">
          <h3 class="title">服务时间</h3>
          <p class="time-desc">请选择您的预约时间，预约时间最早可选支付完成后4小时，您可选择（含今天）五天内的预约时间。</p>
          <time-picker
            :dateTimeTable="dateTable"
            :timeInterval="0.5"
            :selectedItemColor="'#4ECE40'"
            :selectedTabColor="'#fff'"
            :disableText="'暂不可预约'"
            :advanceTime="0"
            :timeSlot="0.5"
            @selectTime="handleSelectTime"
            @selectDateEvent="handleSelectDate"
          ></time-picker>
          <div class="btn-wrapper">
            <van-button color="#4ECE40" block @click="handleConfirm">确认</van-button>
          </div>
        </div>
      </van-popup>
      
      <van-popup position="bottom" :style="{ 'height': actType == 'member' ? '50%' : '90%' }"
      v-model="popupShow">
        <van-picker
          v-if="actType == 'member'"
          title="标题"
          show-toolbar
          value-key="name"
          :columns="jiuzhenArr"
          @confirm="onConfirm"
          @cancel="popupShow = false"
        />
        <!-- <van-picker
          v-else
          title="标题"
          show-toolbar
          value-key="address"
          :columns="addressList"
          @confirm="addressConfirm"
          @cancel="popupShow = false"
        /> -->
        <van-contact-list
          v-else
          v-model="chosenContactId"
          :list="addressList"
          @add="onAdd"
          @select="addressConfirm"
          :add-text="!addressList.length ? '新增' : '确定'"
        />
      </van-popup>

    <div class="common-panel">
      <div class="huli-common-title">
        <h3><em></em>留言</h3>
      </div>

      <van-field
        v-model="form.user_note"
        rows="5"
        autosize
        label=""
        type="textarea"
        maxlength="140"
        placeholder="请描述您的疑问或症状，疾病或身体情况。"
        show-word-limit
        class="textarea"
      />
    </div>

    <div class="common-panel agreement">
      <van-checkbox v-model="checked" shape="square">本人或接受上门服务的人已充分知《用户协议》，同意遵守合同并接受上门服务。</van-checkbox>
    </div>

    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" @click="onClickIcon" />
      <van-goods-action-button
        :color="'linear-gradient(0deg, #FF534F 0%, #FF9C78 100%)'"
        text="提交订单"
        @click="onClickButton"
      />
    </van-goods-action>

    
  </div>
</template>

<script>
import { nurseItemInfoServer,memberList,nurseItemOrderServer,nurseOrderPayment } from '@/service/server';
import { myAddress } from '@/service/user';
import { checkHuliServiceTime } from '@/service/order';
import TimePicker from "@/components/time-picker/index";
import dayjs from 'dayjs';
import Vue from 'vue';
import { ContactList } from 'vant';
import { GetQueryString } from '@/utils/index'
import { mapState, mapGetters } from 'vuex';

Vue.use(ContactList);
export default {
  data() {
    return {
      staticPath: process.env.VUE_APP_STATIC_PATH,
      message:'',
      startTime: '08:00',
      endTime: '22:30',
      dateTable: [],
      actTime:"",
      checked:false,
      actType: '',
      timeShow: false,
      info:{},
      minDate: new Date(1977, 0, 1),
      maxDate: new Date(),
      show: false,
      addressList:[],
      chosenContactId: '',
      popupShow: false,
      member:'',
      address:'',
      jiuzhenArr:[],
      form:{
        user_people_id:'',
        consignee:'',
        province:'',
        city:'',
        district:'',
        address:'',
        mobile:'',
        call_time:'',
        user_note:'',
        // goods_name:'',
        goods_id:'',
        order_amount:''
      }
    };
  },
  created(){
    let query = decodeURIComponent(this.$route.query)
    this.queryInfo(this.$route.query.goods_id);
    this.form.goods_id = this.$route.query.goods_id
    // this.form.goods_name = query.goods_name
    this.queryAddress()
    this.queryAddressList()
    this.queryServiceTime(this.$route.query.goods_id)
    console.log(this.memberInfo,'激活的vuex params')
    this.member = this.memberInfo.name
    this.form.consignee = this.memberInfo.name
    this.form.user_people_id = this.memberInfo.id
    this.form.mobile = this.memberInfo.tel
    this.form.province = this.addressHuli.province
    this.form.city = this.addressHuli.city
    this.form.district = this.addressHuli.district
    this.form.address = this.addressHuli.address
  },
  components: {
    TimePicker
  },

  computed: {
    ...mapGetters(["addressHuli","memberInfo"]),
  },

  activated(){
    console.log(this.memberInfo,'激活的vuex params')
  },

  methods: {
    async queryServiceTime(id){
      let result = await checkHuliServiceTime(id);
      if(result.status == 200){
        let dateTable = result.data;
        dateTable.map(item => {
          item.timeStamp = dayjs(item.date).valueOf()
        })
        this.dateTable = dateTable
        console.log(this.dateTable,'parent data')
      }
    },
    handleConfirm(){
      this.timeShow = false
      this.form.call_time = this.actTime
    },
    
    handleSelectDate(index,item){
      console.log(index,item,'handleSelect')
    },
    handleRouter(){
      this.$router.push({
        path: '/huli/order/select-time',
        query:{
          goods_name: this.$route.query.goods_name,
          goods_id: this.$route.query.goods_id
        }
      })
    },
    onAdd(){
      this.popupShow = false
    },
    handleAddComfirm(arr){
      console.log(arr)
      this.popupShow = false
      let [province,city,district] = arr
      this.form.province = province.code
      this.form.city = city.code
      this.form.district = district.code
      this.form.address = arr.reduce((name,item) => name += item.name, '')
      this.chosenContactId = arr.id
    },
    handleShowPopup(type){
      this.actType = type
      let redirect = encodeURIComponent('/huli/order/index?goods_id=' + GetQueryString('goods_id'))
      if(type == 'member'){
        if(!this.jiuzhenArr.length){
          this.$dialog.confirm({
            title: '提示',
            message: '暂无就诊者，去添加'
          }).then(() => {
            this.$router.push({
              path: '/user/office/index?type=addNew&redirect=' + redirect
            })
          })
          .catch(() => {
            this.$toast('已取消')
          });
        }else{
          this.$router.push({
            path: '/user/office/index?type=select&redirect=' + redirect
          })
        }
      }else{
        // this.popupShow = true
        this.$router.push({
          path: '/user/address/index?type=select&redirect=' + redirect
        })
      }
    },
    async queryAddressList(){
      let result = await myAddress();
      if(result.status == 200){
        if(result.data.model.length > 0) this.addressList = result.data.model.map(item => {
          return {
            ...item,
            isDefault: item.is_default,
            id: item.address_id,
            name: item.consignee + '\n' + item.province_name + item.city_name + item.district_name + item.address,
            tel: item.mobile
          }
        })
      }else{
        this.$toast(result.message)
      }
    },
    async queryAddress(){
      let result = await memberList();
      if(result.status == 200){
        // this.jiuzhenArr = result.data.model
        if(result.data.model.length > 0) this.jiuzhenArr = result.data.model
          
      }else{
        this.$toast(result.message)
      }
    },
    onConfirm(e){
      console.log(e,'confirm')
      this.member = e.name
      this.form.consignee = e.name
      this.form.user_people_id = e.id
      this.form.mobile = e.tel
      this.popupShow = false
    },
    onAdd(){
      if(!this.addressList.length > 0){
        this.$router.push({
          path: '/user/address/index?type=select'
        })
      }
    },
    addressConfirm(e){
      if(this.addressList.length > 0){
        console.log(e)
        this.form.province = e.province
        this.form.city = e.city
        this.form.district = e.district
        this.form.address = e.address
      }else{
        this.$toast('未添加地址 请先添加地址')
        this.$router.push({
          path: 'user/address/index?type=select'
        })
      }
      this.popupShow = false
    },
    birthConfirm(e){
      this.show = false
      this.birthLabel = dayjs(e).format("YYYY-MM-DD");
      this.form.birthday = dayjs(e).format("YYYY-MM-DD");
    },
    handleBirthShowPopup(type){
      this.active = type
      this.show = true
    },
    
    async queryInfo(id){
      let result = await nurseItemInfoServer(id);
      if(result.status == 200){
        this.info = result.data
      }else{
        this.$toast(result.message)
      }
    },
    onClickIcon(){},
    async onClickButton(){
      let params = Object.assign({},this.form);
      delete params.goods_name
      params.order_amount = parseFloat(this.info.price).toFixed(2);
      if(!this.checked) return this.$toast('请勾选已阅读用户协议')
      let result = await nurseItemOrderServer(params);
      if(result.status == 200){
        
        let order_id = result.data[0].order_id;
        
        let parament = result.data[1];
        let payment = await nurseOrderPayment({
          order_id
        });
        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener(
              "WeixinJSBridgeReady",
              this.onBridgeReady(parament),
              false
            );
          } else if (document.attachEvent) {
            document.attachEvent("WeixinJSBridgeReady", this.onBridgeReady(parament));
            document.attachEvent("onWeixinJSBridgeReady", this.onBridgeReady(parament));
          }
        }else{
          this.onBridgeReady(parament);
        }
      }else{
        this.$toast("参数错误：");
      }
    },
    onBridgeReady(json) {
      let that = this;
      WeixinJSBridge.invoke("getBrandWCPayRequest", json, function (res) {
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回 ok，但并不保证它绝对可靠。
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          this.$store.commit('user/SET_HULI_ADDRESS',{})
          this.$store.commit('user/SET_MEMBER_INFO',{})
          that.$router.replace({
            path: '/huli/order/success'
          })
        } else {
          // this.$toast("支付失败，请联系客服...");
          this.$store.commit('user/SET_HULI_ADDRESS',{})
          this.$store.commit('user/SET_MEMBER_INFO',{})
        }
      });
    },

    handleSelectTime(index,item){
      console.log(index)
      if(item[1] !== undefined){
        this.actTime = dayjs(item[1]).format("YYYY-MM-DD HH:mm")
      }else{
        // this.$toast('暂无可选时间')
        this.actTime = ''
      }
      console.log(index,item,'handleSelect')
    },
    handleSelectDate(index,item){
      console.log(index,item,'handleSelect')
    },
  },
  beforeDestroy(){

  }
};
</script>
<style lang='less'>

.order-wrapper{
  background: #f5f5f5;
  .agreement{
    .van-checkbox__label{
      color: #999;
    }
  }
  .textarea{
    background: transparent;
    border: 1px solid #f5f5f5;
  }
  .order-item{
    display: flex;
    justify-content: space-around;
    align-items: center;
    .order-left{
      display: flex;
      justify-content: space-around;
      flex-direction: column;
      flex: 1;
      height: 102px;
      .bottom-con{
        .price-wrapper{
          .price{
            color: #ff0000;
            font-size: 16px;
          }
          .line-price{
            color: #999;
            font-size: 13px;
            margin-left: 10px;
          }
        }
      }
      .top-con{
        height: 80%;
        flex: 1;
        .title{
          font-size: 16px;
          color: #000;
          margin-bottom: 10px;
        }
        .desc{
          color: #999;
          font-size: 13px;
          line-height: 1.5;
          .ellipsisLine(3)
        }
      }
    }
  }
  .common-panel {
    margin-top: 10px;
    background: #fff;
    padding: 15px;
  }
  .panel-cell{
    margin-top: 10px;
    .van-cell{
      background: #fff;
    }
  }
  .huli-common-title {
    margin-bottom: 15px;
    .right-arrow {
      display: flex;
      justify-content: flex-end;
      color: #999;
      font-size: 13px;
      flex: 1;
    }
    h3 {
      font-size: 16px;
      margin-bottom: 15px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      em {
        display: inline-block;
        width: 5px;
        height: 17px;
        background: linear-gradient(0deg, #fcc9cb, #f7757b);
        border-radius: 5px;
        margin-right: 6px;
      }
    }
  }
}

</style>